package com.example;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.SimpleAccountRealm;
import org.apache.shiro.subject.Subject;
import org.junit.Before;
import org.junit.Test;

/**
 * @ClassName QuickStartTest4_2
 * @Description TODO
 * @Author zhaoluowei
 * @Date 2019/6/30  22:36
 * @Version 1.0
 *
 * shiro 授权环节
 */

public class QuickStartTest4_3 {

    private SimpleAccountRealm accountRealm = new SimpleAccountRealm();

    private DefaultSecurityManager securityManager = new DefaultSecurityManager();


    @Before
    public void init() {
        //初始化数据源
        accountRealm.addAccount("zhangsan", "123","root","admin","add","update","delete","query");
        accountRealm.addAccount("lisi", "456","user");
        accountRealm.addAccount("wangwu", "789","user");
        accountRealm.addAccount("jack", "123","yk");

        //构建环境
        securityManager.setRealm(accountRealm);

    }

    //测试授权
    @Test
    public void test() {
        SecurityUtils.setSecurityManager(securityManager);

        //获取当前的主体
        Subject subject = SecurityUtils.getSubject();

        //构造需要登录用户信息 用户用的
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken("zhangsan","123");

        subject.login(usernamePasswordToken);
        System.out.println(" 认证结果 -->  "+subject.isAuthenticated());
        System.out.println(" 是否有对应角色 -->  "+subject.hasRole("add"));
        System.out.println(" Principal  -->  "+subject.getPrincipal());
        subject.logout();
        System.out.println(" 认证结果 -->  "+subject.isAuthenticated());

    }


}
